package com.mku.wms_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mku.wms_service.common.QueryPageParam;
import com.mku.wms_service.common.Response;
import com.mku.wms_service.dto_vo.LoginDTO;
import com.mku.wms_service.entity.User;
import com.mku.wms_service.mapper.UserMapper;
import com.mku.wms_service.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author maoxx
 * @since 2024-11-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Response<User> login(LoginDTO loginDTO) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("no", loginDTO.getNo());

        User user = getOne(qw);

        if (user == null) {
            return Response.fail("用户不存在");
        }

        if (!user.getPassword().equals(loginDTO.getPassword())) {
            return Response.fail("密码错误");
        }

        return Response.success(user);
    }

    @Override
    public Response<User> findByNo(String no) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("no", no);
        User one = getOne(qw);

        if (one == null) {
            return Response.fail("用户不存在");
        }
        return Response.success();
    }

    @Override
    public Response<Page<User>> listPage(QueryPageParam qp2) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        String name = (String) qp2.getParam().get("name");
        String sex = (String) qp2.getParam().get("sex");
        Page<User> page = new Page<>();
        page.setCurrent(qp2.getPageNum());
        page.setSize(qp2.getPageSize());

        if (name != null && !"".equals(name.trim())) {
            qw.like("name", name);
        }

        if (sex != null && !"".equals(sex.trim())) {
            qw.eq("sex", sex);
        }

        if (qp2.getValue() == 0) {
            qw.in("role_id", 0,1);
        } else {
            qw.eq("role_id", 2);
        }

        Page<User> pages = page(page, qw);

        return Response.success(pages);
    }


    @Override
    public Response<User> delete(Integer id) {
        boolean b = removeById(id);
        return b ? Response.success() : Response.fail("删除失败");
    }

    @Override
    public Response<User> add(User user) {
        User byId = getById(user.getId());
        if (byId == null) {
            user.setRoleId(2);
        }
        return saveOrUpdate(user) ? Response.success() : Response.fail("操作失败");
    }

}
